<template>
  <van-popup
    v-model="show"
    position="left"
    class="fa"
    :style="{ height: '100%', width: '100%' }"
  >
    <div>
      <van-nav-bar
        title="报价管理"
        left-text="返回"
        left-arrow
        @click-left="onClickLeft"
      />
      <div class="client">
        <van-field
          v-if="!this.Id"
          label="客户名称："
          v-model="entity.CustomerName"
          readonly
          placeholder="请选择客户"
        >
        </van-field>
        <van-field
          label="价格表名称："
          v-model="entity.PriceListName"
          readonly
          @click="PriceList"
          placeholder="请选择价格表"
          right-icon="edit"
          @click-right-icon="PriceList"
        ></van-field>
        <van-field
          v-model="entity.Discount"
          label="折扣"
          placeholder="请输入折扣"
        />
        <van-field
          readonly
          v-model="entity.TotalAmount"
          label="折扣后金额"
          placeholder="根据折扣计算"
        />
      </div>
      <div class="scrollBar">
        <div class="Pricebox" v-for="item in data" :key="item.Id">
          <div class="left">
            品名:<span class="font"
              >{{ item.ProductId }}/{{ item.cInvName }}</span
            >
          </div>

          <div class="left">
            规格:<span class="font">{{ item.cInvStd || "无" }}</span>
          </div>
          <span class="Fa">
            <!-- <van-field label="数量:" v-model="item.ProductIdNum" /> -->
            <span class="left">数量:</span>
            <van-stepper class="fontstepper" v-model="item.ProductIdNum" />
          </span>
          <div class="Fa">
            <span><van-field label="税率%:" v-model="item.TaxRate"/></span>
            <van-field label="含税价格:" v-model="item.Tax_Included_Price" />
          </div>
        </div>
      </div>
    </div>
    <Myuser @customerChoice="Client" ref="myuser" />
    <ProductPriceList @Product="Product" ref="product" />
    <PriceList ref="PriceList" @PriceList="Price" />
    <div
      :style="{
        position: 'absolute',
        right: 0,
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e9e9e9',
        padding: '5px 0px',
        background: '#fff',
        textAlign: 'right',
        zIndex: 1
      }"
    >
      <span class="spanfont"
        >金额合计: <i class="price"> {{ a }}</i>
      </span>
      <!-- &nbsp;&nbsp;&nbsp;&nbsp; -->
      <div style="margin-top:5px">
        <van-button @click="Add" slot="button" type="info">添加产品</van-button>
        <van-button
          style="margin-left:8px"
          @click="close"
          slot="button"
          type="default"
          >关闭</van-button
        >
        <van-button
          style="margin:0px 10px"
          @click="handleSubmit"
          slot="button"
          type="primary"
          >保存</van-button
        >
      </div>
    </div>
  </van-popup>
</template>

<script>
import { Icon } from "vant";
import { Popup } from "vant";
import { AddressList } from "vant";
import PriceList from "../../components/PriceList.vue";
import {
  Row,
  Col,
  Cell,
  CellGroup,
  Stepper,
  Toast,
  NavBar,
  Divider
} from "vant";
import { Field } from "vant";
//客户
import Myuser from "@/components/OwnUser.vue";
import ProductPriceList from "../../components/ProductPriceList.vue";
export default {
  watch: {
    data: {
      handler(n, o) {
        //console.log(n, o)
        this.$nextTick(() => {
          //金额
          this.a = 0;

          //含税价
          this.j = 0;

          //不含税价
          this.n = 0;
          this.TaxAll = 0;
          n.length > 0 &&
            n.forEach(item => {
              if (Number(item.ProductIdNum) < 0) {
                Toast("数量不能小于0");
                this.$set(item, "ProductIdNum", 1);
              }
              if (Number(item.TaxRate) < 0) {
                Toast("税率不能小于0");
                this.$set(item, "TaxRate", 1);
              }
              if (Number(item.Tax_Included_Price) < 0) {
                Toast("价格不能小于0");
                this.$set(item, "Tax_Included_Price", 1);
              }
              this.j += Number(item.Tax_Included_Price);
              this.n += Number(item.Tax_Excluded_Price);
              //金额
              item.Amounts = item.ProductIdNum * item.Tax_Included_Price;
              //不含税价格
              item.Tax_Excluded_Price =
                item.Tax_Included_Price -
                item.Tax_Included_Price * (item.TaxRate / 100);

              //税金/
              item.Tax =
                item.Tax_Included_Price -
                item.Tax_Included_Price / (item.TaxRate / 100 + 1);

              this.TaxAll += Number(item.Tax);
              // console.log(this.TaxAll)
              // item.Tax = (item.Tax_Included_Price - item.Tax_Excluded_Price) * item.ProductIdNum
              this.a += Number(item.Amounts);
            });

          this.j = this.j.toFixed(2);
          if (this.a) {
            this.a = this.a.toFixed(2);
            this.entity.TotalAmount = this.a * (this.entity.Discount / 100);
            this.entity.TotalAmount = this.entity.TotalAmount.toFixed(2);
            this.entity.Taxes = this.TaxAll * (this.entity.Discount / 100);
            this.entity.Taxes = this.entity.Taxes.toFixed(2);
          } else {
            this.a = 0;
          }
        });

        //console.log(this.a)
      },
      deep: true,
      immediate: true
    },

    // 'entity.Object': {
    //   handler(newVal, oldVal) {
    //     if (newVal) {
    //       //console.log(newVal, oldVal)
    //       this.$set(this.entity, 'LinkMan', '')
    //       this.contactPerson(newVal.cCusCode)

    //       this.entity.AccountManager = this.op().RealName
    //     }
    //     if (oldVal) {
    //       this.cc = true
    //     }
    //   },
    //   deep: true
    // },
    "entity.Freight": {
      handler(newVal, oldVal) {
        //console.log(newVal, oldVal)

        if (newVal < 0) {
          this.$set(this.entity, "Freight", 1);
          return Toast("运费不可以小于0");
        }
      },
      deep: true,
      immediate: true
    },
    "entity.Discount": {
      handler(newVal, oldVal) {
        //console.log(newVal)
        if (newVal > 100) {
          this.$set(this.entity, "Discount", 100);
          return Toast("折扣不可以大于100");
        }
        if (newVal < 0) {
          this.$set(this.entity, "Discount", 1);
          return Toast("折扣不可以小于0");
        }
        if (newVal) {
          // this.$set(this.entity, 'TotalAmount', this.a - this.a * (this.entity.Discount / 100))
          this.entity.TotalAmount = this.a * (this.entity.Discount / 100);
          this.entity.TotalAmount = this.entity.TotalAmount.toFixed(2);
          this.entity.Taxes = this.TaxAll * (this.entity.Discount / 100);
          this.entity.Taxes = this.entity.Taxes.toFixed(2);
        }
      },
      deep: true,
      immediate: true
    }
  },

  components: {
    "van-stepper": Stepper,
    //分割线
    "van-divider": Divider,
    "van-nav-bar": NavBar,
    "van-icon": Icon,
    "van-popup": Popup,
    "van-row": Row,
    "van-address-list": AddressList,
    "van-field": Field,
    "van-col": Col,
    "van-cell": Cell,
    "van-cell-group": CellGroup,
    Myuser,
    ProductPriceList,
    PriceList
  },
  data() {
    return {
      entity: {},
      data: [],
      queryParam: {},
      show: false,
      a: 0,
      Id: "",
      TaxAll: 0
    };
  },
  methods: {
    //返回
    onClickLeft() {
      this.show = false;
    },
    //选中的产品
    Product(a) {
      var ar = [];
      a = [a];
      this.data.forEach(item => {
        a.forEach((val, i) => {
          if (item.ProductId == val.ProductId) {
            ar.push(val);
            delete a[i];
          }
        });
      });
      //console.log(ar)

      if (ar.length == 0) {
        a.forEach(item => {
          //console.log(this.data)

          this.data.push({
            ProductId: item.ProductId,
            cInvName: item.cInvName,
            cInvCode: item.cInvCode,
            cInvStd: item.cInvStd,
            Tax_Included_Price: item.StandardPrice,
            TaxRate: 13,
            ProductIdNum: 1
          });
        });
        //console.log(ar)
        // this.data = [...this.data, ...a]
      } else {
        Toast.fail("重复产品已筛选掉");
        a.forEach(item => {
          console.log(item);
          this.data = [...this.data, item];
        });
      }
    },
    Price(a) {
      console.log(a);
      this.$set(this.entity, "PriceListName", a.ListName);
      this.$set(this.entity, "PriceListId", a.Id);
    },
    PriceList() {
      this.$refs.PriceList.openForm();
    },
    // 选择产品;
    Add() {
      if (this.entity.PriceListId) {
        this.$refs.product.openForm(this.entity.PriceListId);
      } else {
        Toast("请先选择价格表");
        return;
      }
    },
    close() {
      this.show = false;
    },
    Client(a) {
      console.log(a);
      this.$set(this.entity, "CustomerName", a.cCusName);
      console.log(this.entity.CustomerName);
      // this.entity.CustomerName = a.cCusName;
      this.entity.CustomerId = a.cCusCode;
    },
    //选择客户
    CustomerChoice() {
      // console.log(123);
      this.$refs.myuser.openForm();
    },
    getDataList() {
      this.http
        .post("/QuotationManagement/Quot_OfferSheetMain/GetTheDataOfAll", {
          // PageIndex: this.pagination.current,
          // PageRows: this.pagination.pageSize,
          SortField: "Id",
          SortType: "desc",
          Search: {
            Condition: "Id",
            Keyword: this.Id
          }
        })
        .then(res => {
          if (res.Success) {
            this.entity = res.Data;

            this.data = res.Data.QOSD_List;
          } else {
            Toast(res.Msg);
          }
        });
    },
    // getPriceList() {
    //   this.selectedRowKeys = [];

    //   this.http
    //     .post(
    //       "/QuotationManagement/Quot_OfferSheetMain/GetDataListByConditions",
    //       {
    //         PageIndex: 1,
    //         PageRows: 99,
    //         SortField: "Id",
    //         SortType: "asc",
    //         Search: [this.queryParam]
    //       }
    //     )
    //     .then(resJson => {
    //       this.data = resJson.Data;
    //     });
    // },
    init() {
      this.Id = "";
      this.show = true;
      (this.data = []), (this.entity = {});
      var num = "";
      for (var i = 0; i < 3; i++) {
        num += Math.floor(Math.random() * 10);
      }
      let yy = new Date().getFullYear();
      let mm = new Date().getMonth() + 1;
      let dd = new Date().getDate();
      let hh = new Date().getHours();
      let mf =
        new Date().getMinutes() < 10
          ? "0" + new Date().getMinutes()
          : new Date().getMinutes();
      let ss =
        new Date().getSeconds() < 10
          ? "0" + new Date().getSeconds()
          : new Date().getSeconds();
      var gettime = `${yy}${mm}${dd}${hh}${mf}${ss}${num} `;

      this.$set(this.entity, "QuotationNo", gettime);
    },
    handleSubmit() {
      var entityData = { ...this.entity };
      var QOSD_List = [...this.data];
      entityData.QOSD_List = QOSD_List;
      // console.log(entityData);
      this.http
        .post("/QuotationManagement/Quot_OfferSheetMain/SaveData", entityData)
        .then(resJson => {
          console.log(resJson);

          if (resJson.Success) {
            Toast(resJson.Msg);
            this.show = false;

            console.log(this.$parent);
            // this.getPriceList();
          } else {
            Toast(resJson.Msg);
          }
        });
    },
    openForm(name, code) {
      this.init();
      this.entity.CustomerName = name;
      this.entity.CustomerId = code;
    }
  }
};
</script>

<style scoped>
.price {
  color: red;
}
.fontstepper {
  margin-left: 15px;
  line-height: 40px;
}
.spanfont {
  margin-left: 10px;
  float: left;
  line-height: 55px;
}
.left {
  margin: 10px 0px 10px 15px;
  /* margin-left: 15px; */
}
.font {
  margin-left: 15px;
  font-size: 18px;
}
.scrollBar {
  /* height: 550px; */
  height: calc(100vh - 220px);
  /* padding-bottom: 80px; */
  overflow: auto;
}
.close {
  position: "absolute";

  right: 0;
  bottom: 0;
  padding: "5px 16px";
  background: "#fff";
  text-align: right;
  z-index: 1;
}
.client {
  box-shadow: rgba(128, 128, 128, 0.1) 10px 10px 5px 5px;
}
.Pricebox {
  box-shadow: 2px 2px 5px #ccc;
  border-radius: 5px;
  width: 95%;
  /* height: 170px; */

  margin: 0 auto;

  border: 1px solid #ccc;
  /* box-shadow: rgba(128, 128, 128, 0.1) 10px 10px 10px 10px; */

  margin-top: 20px;
  margin-bottom: 10px;
}
.Fa {
  display: flex;
  justify-content: left;
}
</style>
